import {
  AxiosConfig,
  AxiosResponse,
  AxiosRequestHeaders,
  AxiosError,
  InternalAxiosRequestConfig
} from './types'
import { showFailToast, showConfirmDialog } from 'vant'
import qs from 'qs'
import { useStorage } from '@/hooks/web/useStorage'
import { resetRouter } from '@/router'
import router from '@/router'

const { getStorage, clear } = useStorage()

const config: AxiosConfig = {
  /**
   * api请求基础路径
   */
  baseUrl: {
    // 开发环境接口前缀
    base: '',

    // 打包开发环境接口前缀
    dev: '',

    // 打包生产环境接口前缀
    pro: 'https://www.xingtuobao.com/control/h5', //'https://www.xingtuobao.com/control/h5',

    // 打包测试环境接口前缀
    test: ''
  },

  /**
   * 接口成功返回状态码
   */
  code: 200,

  /**
   * 接口请求超时时间
   */
  timeout: 60000,

  /**
   * 默认接口请求类型
   * 可选值：application/x-www-form-urlencoded multipart/form-data
   */
  defaultHeaders: 'application/json',

  interceptors: {
    //请求拦截
    // requestInterceptors: (config) => {
    //   return config
    // },
    // 响应拦截器
    // responseInterceptors: (result: AxiosResponse) => {
    //   return result
    // }
  }
}

const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (
    config.method === 'post' &&
    (config.headers as AxiosRequestHeaders)['Content-Type'] === 'application/x-www-form-urlencoded'
  ) {
    config.data = qs.stringify(config.data)
  }
  if (config.method === 'get' && config.params) {
    let url = config.url as string
    url += '?'
    const keys = Object.keys(config.params)
    for (const key of keys) {
      if (config.params[key] !== void 0 && config.params[key] !== null) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
    }
    url = url.substring(0, url.length - 1)
    config.params = {}
    config.url = url
  }
  // if (getStorage('token')) {
  //   config.headers.token = getStorage('token')
  // }
  return config
}
;(error: AxiosError) => {
  Promise.reject(error)
}
let isReLogin = false

const defaultResponseInterceptors = (response: AxiosResponse<any>) => {
  console.log('response', response)
  if (response?.config?.responseType === 'blob') {
    // 如果是文件流，直接过
    return response
  } else if (response.data.success) {
    return response.data
  } else if (response.data.hash && response.data.key) {
    return response.data
  }
  // else if(response.status === config.code&&response.data.statusCode===config.code){
  //   return response.data
  // }
  else if (!response.data.success) {
    showFailToast(response.data.message)
  } else {
    showFailToast(response.data.message)
  }
}
;(error: AxiosError) => {
  console.log('err' + error) // for debug
  showFailToast(error.message)
  return Promise.reject(error)
}

export { defaultResponseInterceptors, defaultRequestInterceptors }
export default config
